﻿using System;

class MaximalElementInPortionOfArray
{
    //Exercise 9.
    //Write a method that return the maximal element in a portion of array of integers starting at given index. 
    //Using it write another method that sorts an array in ascending / descending order.

    static void Main()
    {
        //initialize the array
        Console.Write("Number of elements = ");
        int size = int.Parse(Console.ReadLine());
        int[] array = new int[size];
        Random random = new Random();
        for (int i = 0; i < size; i++)
        {
            array[i] = random.Next(0, 100);
        }
        //print the array
        PrintArray(array);

        Console.WriteLine("Enter the start index of the array portion: ");
        int startIndex = int.Parse(Console.ReadLine());

        Console.WriteLine("Maximal element:  {0}", array[MaxIndex(array, startIndex)]);

        DescendingOrder(array);
        PrintArray(array);

        Array.Reverse(array);
        PrintArray(array);
    }

    private static void PrintArray(int[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write(array[i] + " ");
        }
        Console.WriteLine();
    }

    private static void DescendingOrder(int[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            int max = MaxIndex(array, i);
            SwitchElements(array, i, max);
        }
    }

    private static void SwitchElements(int[] array, int firstElement, int secondElement)
    {
        int tempElement = array[firstElement];
        array[firstElement] = array[secondElement];
        array[secondElement] = tempElement;
    }

    private static int MaxIndex(int[] array, int startIndex)
    {
        int maxElement = 0;
        int maxIndex = 0;
        for (int i = startIndex; i < array.Length; i++)
        {
            if (array[i] > maxElement)
            {
                maxElement = array[i];
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}

